// 购物车模块
import { defineStore } from "pinia";
import { computed, ref } from 'vue'
import { useUserStore } from "./user";
import { addCartAPI, findNewCartListApi,delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    const cartList = ref([])
    // 获取最新购物车列表
    const updateCartList = async () => {
        const res = await findNewCartListApi()
        cartList.value = res.result
    }
    // 加入购物车
    const addCart = async (goods) => {

        const { skuId, count } = goods

        // 判断是否登录
        if (isLogin.value) {
            console.log('登录',isLogin,userStore.userInfo.token);
            await addCartAPI({ skuId, count })
            updateCartList()
        } else {
            //已经添加过count加一，没添加过就push
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                // 找到了
                console.log('找到相同得');

                item.count = item.count + goods.count
            } else {
                cartList.value.push(goods)
            }
        }
    }
    // 删除购物车
    const deleteCart = async(skuId) => {
        if (isLogin) {
            await delCartAPI([skuId]) 
            updateCartList()
        } else {
            // 找到要删除的下标值 -splic
            const idIndex = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(idIndex, 1)
            // cartList.value=cartList.value.filter(item)
        }
    }
    // 清除购物车
    const clearCart = () => {
        console.log('清除购物');
        
        cartList.value = []
    }
    // 计算属性
    // 总数量
    const allCount = computed(() => cartList.value.reduce((a, b) => a + b.count, 0)
    )
    // 总价格
    const allPrice = computed(() => cartList.value.reduce((a, b) => a + b.count * b.price, 0)
    )
    return { cartList, addCart, deleteCart, allCount, allPrice ,clearCart,updateCartList}
}, {
    persist: true
})